<template>
  <div>
    <img
      :src="userinfo ? userinfo.avatar.replace(/public/, $baseURL) : pic"
      alt=""
      style="border-radius: 50%; width: 67px; height: 67px; margin-right: 20px"
      @click="uploadAction"
    />
    <input type="file" class="input-file" ref="upload" @change="startUpload" />
  </div>
</template>

<script>
import { mapState, mapMutations } from 'vuex'

export default {
  name: 'uploadAvatar',
  components: {},
  data () {
    return {
      pic: require('@/assets/center-portrait.png')
    }
  },
  computed: { ...mapState('login', ['userinfo']) },
  created () {},
  mounted () {
    // 获取个人信息是异步的，写在这头像不出来
    // if (this.userinfo) {
    //   this.pic = this.userinfo.avatar.replace(/public/, this.$baseURL);
    // } else {
    //   this.pic = require("@/assets/center-portrait.png");
    // }
  },
  methods: {
    ...mapMutations('login', ['changeUserInfo']),
    uploadAction () {
      if (this.userinfo) {
        this.$refs.upload.click()
      }
    },
    startUpload () {
      console.log(this.$refs.upload.files)

      const file = this.$refs.upload.files[0]
      console.log(file)
      var data = new FormData()
      data.append('avatar', file) // 上传文件需要表达对象， js 实例化一个表单对象
      this.$ajax.sendavatar(data).then((res) => {
        console.log(res)
        if (res.code == 200) {
          this.changeUserInfo({
            avatar: res.avatar
          })
        }
      })
    }
  }
}
</script>

<style scoped lang="scss">
.input-file {
  display: none;
}
</style>
